package cn.zniot.so.application.service;

import cn.zniot.so.application.SessionManager;
import cn.zniot.so.application.constant.Constants;
import cn.zniot.so.application.util.PropertyUtil;
import cn.zniot.so.transport.asynpack.Zniot2PacketC;
import cn.zniot.so.transport.asynpack.ZniotPacketC;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

import java.util.concurrent.ConcurrentHashMap;

public class ControlSyncManager {
	private static Logger logger = Logger.getLogger(ControlSyncManager.class);
	private static ControlSyncManager instance = null;
	public static int FLAG = 0;

	public synchronized static ControlSyncManager getInstance() {
		if (instance == null) {
			instance = new ControlSyncManager();
		}
		return instance;
	}

	// private static byte TBOXBEGIN = '<';
	// private static byte TBOXEND = '>';
	// private byte[] messages ;
	private static ConcurrentHashMap<String, String> sessionMessages = new ConcurrentHashMap<String, String>();

	public synchronized String getMessages(String IpAndPort) {
		String message = sessionMessages.get(IpAndPort);
		if (message != null) {
			sessionMessages.remove(IpAndPort);
		}
		return message;
	}

	public synchronized void setMessages(String IpAndPort, String messages) {
		sessionMessages.put(IpAndPort, messages);
	}

	public synchronized String getIpAndPortByimse(String imse) {
		// logger.debug("getIpAndPortByimse by imse :" + imse);
		String ipAndPort = PropertyUtil.getInstance().getIpPortByIMEI(imse);
		if (ipAndPort == null) {
			// logger.debug("not find ipAndPort");
		} else {
			// logger.debug("imse:" + imse + " find ipAndPort:" + ipAndPort);
		}
		return ipAndPort;
	}

	/**
	 * 发送指令到盒子
	 * 
	 * @param cmd
	 *            :指令
	 * @param imse
	 *            :Zniot IMEE号
	 * @return
	 */
	public String Synccmd2Box(String cmd, String imse) {
		// logger.debug("Send cmd:" + cmd + " by imse :" + imse);
		try {
			String ipAndPort = ControlSyncManager.getInstance()
					.getIpAndPortByimse(imse);
			if (ipAndPort == null) {
			    if (logger.isDebugEnabled()) {
			        logger.debug("not find ipAndPort");
			    }
				return null;
			}
			IoSession boxiosession = SessionManager.getInstance().getSession(
					ipAndPort);
			if (boxiosession == null) {
			    if (logger.isDebugEnabled()) {
			        logger.debug("not find IoSession");
			    }
				return null;
			}
			ZniotPacketC packet = new ZniotPacketC();
			packet.setCode(cmd);
			boxiosession.write(packet);
			int loop = 0;
			while (loop < 2) {
				String message = ControlSyncManager.getInstance().getMessages(
						ipAndPort);
				if (message != null) {
					return message;
				}
				Thread.sleep(Constants.HEARTBEAT);// TODO
															// 这个参数需要提出到配置文件中
				loop++;
			}
			return null;
		} catch (Exception e) {
			logger.error("error " + e);
			return null;
		}
	}

	/**
	 * 发送指令到盒子
	 * 
	 * @param cmd
	 *            :指令
	 * @param imse
	 *            :Zniot IMEE号
	 * @return
	 */
	public byte[] Syncinfo2Box(String cmd, String imse) {
		// logger.debug("Send cmd:" + cmd + " by imse :" + imse);
		try {
			String ipAndPort = ControlSyncManager.getInstance()
					.getIpAndPortByimse(imse);
			if (ipAndPort == null) {
			    if (logger.isDebugEnabled()) {
			        logger.debug("not find ipAndPort");
                }
				return null;
			}
			int loop = 0;
			try {
				while (loop < 3) {
					IoSession boxiosession = SessionManager.getInstance()
							.getSession(ipAndPort);
					if (boxiosession != null && FLAG != 1) {
						Zniot2PacketC packet = null;
						packet = new Zniot2PacketC();
						// packet.setCode(new BigInteger(cmd,16).toByteArray());
						packet.setCode((cmd + "\r\n").getBytes("UTF-8"));
						boxiosession.write(packet);
						FLAG = 1;
					}

					String message = ControlSyncManager.getInstance()
							.getMessages(ipAndPort);
					if (message != null) {
						String[] contents;
						try {
							contents = message.split("\r");
						} catch (Exception e) {
							return message.getBytes("UTF-8");
						}
						if (contents.length >= 2) {
							message = contents[1];
						} else {

						}
						return message.getBytes("UTF-8");
					}
					Thread.sleep(Constants.HEARTBEAT);
					loop++;
				}
			} catch (Exception e) {
				logger.error("error " + e);
			}
		} catch (Exception e) {
			logger.error("error " + e);
			return null;
		}
		return null;
	}

}
